package cloud.lysky.java.on.concurrent.lock.locksupport;

import java.util.concurrent.locks.LockSupport;

/**
 * @author luoly
 * @describe
 * @date 2023-04-14 12:10
 **/
// 使用LockSupport实现线程顺序执行，打印ABC
public class OrderPrint {

    private void printA(Thread t) {
        try{
            Thread.sleep(5L);
            System.out.print("A");
            LockSupport.unpark(t);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    private void printB(Thread t) {
        try{
            Thread.sleep(5L);
            LockSupport.park();
            System.out.print("B");
            LockSupport.unpark(t);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void printC() {
        try{
            Thread.sleep(5L);
            LockSupport.park();
            System.out.print("C");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        OrderPrint orderPrint = new OrderPrint();
        Thread threadC = new Thread(orderPrint::printC);
        Thread threadB = new Thread(() -> {
            orderPrint.printB(threadC);
        });
        Thread threadA = new Thread(() -> {
            orderPrint.printA(threadB);
        });
        threadA.start();
        threadB.start();
        threadC.start();
    }
}
